package com.xiaoyu.client.ui.activity.main.mine.my_order;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.techfansy.bottomDialog.BottomDialog;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.PayResult;
import com.xiaoyu.client.model.mine.ParticularsBean;
import com.xiaoyu.client.model.order.OrderBean;
import com.xiaoyu.client.model.order.OrderBean.DataBean.OrderParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.mall.OrderComfirmActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.ui.base.BaseFragment;
import com.xiaoyu.commonlib.ui.dialog.TitleDetailsDialog;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author jx
 * @date 创建时间 2018/10/19
 * @Description 待付款
 */
public class OrderFragment extends BaseFragment {
    public static final String ORDER_INFO = "order info";
    public static final String ORDER_DETAILS = "order_details";
    private static final int SDK_PAY_FLAG = 1;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.common_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.common_recycler_view_empty_page)
    ImageView mEmptyImg;

    private static final String ARG_PARAM = "param";
    private String mParam;
    private View mView;
    private AllPowerfulAdapter mOrderAdapter;
    private List<OrderBean.DataBean.OrderParam> mOrderList = new ArrayList<>();
    private int page = 1;
    private int totalPage;
    private String state;//订单状态 1未付款，2待发货，3待收货，4待评价，5已评价，6订单售后处理，7售后完成，8订单完成

    public OrderFragment newInstance(String param) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.common_recycler_view, container, false);
            ButterKnife.bind(this, mView);
            initView();
            requestPermission();
        }
        return mView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam = getArguments().getString(ARG_PARAM);
        }
        if (mParam.equals("order0")) {
            state = "1";
        } else if (mParam.equals("order1")) {
            state = "2";
        } else if (mParam.equals("order2")) {
            state = "3";
        } else if (mParam.equals("order3")) {
            state = "4";
        } else if (mParam.equals("order4")) {
            state = "8";
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        getOrderList();
    }

    @SuppressLint("ResourceAsColor")
    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setBackgroundColor(getResources().getColor(R.color.color_gray_F3));
        setObligationAdapter(mOrderList);
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context).setDrawableSize(20);
            }
        });

    }


    //设置适配器
    private void setObligationAdapter(List<OrderBean.DataBean.OrderParam> mOrderList) {
        mOrderAdapter = new AllPowerfulAdapter<OrderBean.DataBean.OrderParam>(R.layout.order_item, mOrderList, new AllPowerfulAdapter.OnClickListener<OrderParam>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, OrderParam orderParam, int position) {
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, OrderBean.DataBean.OrderParam orderParam) {
                super.convert(baseViewHolder, orderParam);
                ImageView goodsdeimg = baseViewHolder.getView(R.id.collect_shop_item_img);
                Glide.with(getActivity()).load(orderParam.getGoodsdeimg()).into(goodsdeimg);//商品展示图
                baseViewHolder.setText(R.id.collect_order_item_explain, orderParam.getGoodsname());//商品名字
                baseViewHolder.setText(R.id.collect_order_item_model, orderParam.getGoodsdetailsname());//规格
                baseViewHolder.setText(R.id.collect_order_item_sprice, "¥   " + orderParam.getGoodsprice());//商品单价
                baseViewHolder.setText(R.id.collect_order_item_num, "共" + orderParam.getGoodsnumber() + "件商品       合计：¥  " + orderParam.getOrdermoney());

                TextView myOrder = baseViewHolder.getView(R.id.my_order_item_txt);
                TextView payment = baseViewHolder.getView(R.id.payment);
                TextView mApplyAfter = baseViewHolder.getView(R.id.apply_for_after_sale);
                RelativeLayout mOrderDetails = baseViewHolder.getView(R.id.order_item_details);
                setItem(myOrder, payment, mOrderDetails, mApplyAfter, orderParam);
            }
        };
        mRecyclerView.setAdapter(mOrderAdapter);
    }

    private void setItem(TextView myOrder, final TextView mPayment, RelativeLayout mOrderDetails, TextView mApplyAfter, final OrderParam orderParam) {
        if (mParam.equals("order0")) {//待付款
            myOrder.setText("取消订单");
            mPayment.setText("付款");
            myOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setOrderDialog(orderParam.getOrderid());
                }
            });
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setPayDialog(orderParam.getOrderid());
                }
            });
            //跳转订单详情页面
            mOrderDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), ExamineOrderActivity.class);
                    intent.putExtra(ORDER_INFO, (Serializable) orderParam);
                    intent.putExtra(ORDER_DETAILS, "order0");
                    startActivity(intent);
                }
            });
        }
        if (mParam.equals("order1")) {//待发货
            myOrder.setText("查看订单");
            mPayment.setText("申请退款");
            myOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ExamineOrderActivity.class);
                    intent.putExtra(ORDER_INFO, (Serializable) orderParam);
                    intent.putExtra(ORDER_DETAILS, "order1");
                    startActivity(intent);
                }
            });
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getContext(), SelectServiceTypeOneActivity.class));
                }
            });
            //跳转订单详情页面
            mOrderDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), ExamineOrderActivity.class);
                    intent.putExtra(ORDER_INFO, (Serializable) orderParam);
                    intent.putExtra(ORDER_DETAILS, "order1");
                    startActivity(intent);
                }
            });
        }
        if (mParam.equals("order2")) {//待收货
            myOrder.setText("查看物流");
            mPayment.setText("确认收货");

            myOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), LookLogisticsActivity.class));
                }
            });
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    confirmReceiptDialog(orderParam.getOrderid());
                }
            });
            //跳转订单详情页面
            mOrderDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), ExamineOrderActivity.class);
                    intent.putExtra(ORDER_INFO, (Serializable) orderParam);
                    intent.putExtra(ORDER_DETAILS, "order2");
                    startActivity(intent);
                }
            });
        }
        if (mParam.equals("order3")) {//待评价
            mApplyAfter.setVisibility(View.GONE);
            myOrder.setText("查看物流");
            mPayment.setText("评价");
            mApplyAfter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getContext(), SelectServiceTypeOneActivity.class));
                }
            });
            myOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), LookLogisticsActivity.class));
                }
            });
            mPayment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), EvaluateActivity.class);
                    intent.putExtra(ORDER_INFO, orderParam);
                    startActivity(intent);
                }
            });
            //跳转订单详情页面
            mOrderDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), ExamineOrderActivity.class);
                    intent.putExtra(ORDER_INFO, (Serializable) orderParam);
                    intent.putExtra(ORDER_DETAILS, "order3");
                    startActivity(intent);
                }
            });
        }
        if (mParam.equals("order4")) {//已完成
            myOrder.setText("查看物流");
            mPayment.setText("已评价");
            myOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), LookLogisticsActivity.class));
                }
            });

            //跳转订单详情页面
            mOrderDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), ExamineOrderActivity.class);
                    intent.putExtra(ORDER_INFO, (Serializable) orderParam);
                    intent.putExtra(ORDER_DETAILS, "order4");
                    startActivity(intent);
                }
            });
        }
    }


    //弹窗(取消订单)
    private void setOrderDialog(final String orderId) {
        new TitleDetailsDialog(getContext(), getResources().getString(R.string.whether_to_cancel_the_order), new TitleDetailsDialog.OnClickListener() {
            @Override
            public void setOnClick() {
                ToastUtil.showToast(getContext(), "取消订单");
                getOrderState("0", orderId);

            }
        }).show();
    }

    //弹窗(确认收货)
    private void confirmReceiptDialog(final String orderId) {
        new TitleDetailsDialog(getContext(), getResources().getString(R.string.confirm_receipt), new TitleDetailsDialog.OnClickListener() {
            @Override
            public void setOnClick() {
                ToastUtil.showToast(getContext(), "确认收货");
                //TODO:确认收货状态变化
                getOrderState("4", orderId);
            }
        }).show();
    }

    //弹窗（选择支付方式）
    private void setPayDialog(final String orderId) {
        new BottomDialog(getContext()).addItemSheet(R.string.alipay, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                //TODO:支付宝支付
                commitOrder(orderId, "ali");

            }
        }).addItemSheet(R.string.wechat, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                //TODO:微信支付
                commitOrder(orderId, "wx");
            }
        }).setCancel(new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
            }
        }).show();
    }

    /**
     * 获取订单列表 -- 根据订单状态
     */
    private void getOrderList() {
        NetworkManager.getOrderList(state, page, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseOrderInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    private void parseOrderInfoSuc(String result) {
        if (page == 1) {
            mOrderList.clear();
        }
        OrderBean bean = new Gson().fromJson(result, OrderBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        mOrderList.addAll(bean.getData().getList());
        if (mOrderList.size() == 0) {
            mRecyclerView.setVisibility(View.GONE);
            mEmptyImg.setVisibility(View.VISIBLE);
            mEmptyImg.setImageResource(R.mipmap.order_empty);
        }
        mOrderAdapter.notifyDataSetChanged();
        if (totalPage <= 1) {
            mRefreshLayout.setEnableLoadMore(false);
        } else {
            mRefreshLayout.setEnableLoadMore(true);
        }
    }


    //调取接口判断订单状态
    private void getOrderState(String orderstate, String orderId) {
        NetworkManager.stateChange(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), orderId, orderstate, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                getOrderList();
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }


    /**
     * 提交订单
     */
    private void commitOrder(String orderId, final String payWay) {
        NetworkManager.toCommitUnpayOrder(orderId, payWay, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ToastUtil.logResult("支付接口", result);
                if (payWay.equals("wallet")) {//余额支付
                    ToastUtil.logResult("订单支付", result);
                    return;
                }
                String orderInfo = null;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    orderInfo = jsonObject.getString("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (payWay.equals("wx")) {//微信支付

                }
                if (payWay.equals("ali")) {//支付宝支付
                    toAliPay(orderInfo);
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                //TODO:待支付接口报错
                ToastUtil.logError("支付接口", errorCode, errorDiscription);
            }
        });
    }


    /**
     * 支付(支付宝)
     */
    private void toAliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus，为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        ToastUtil.showToast(getActivity(), "支付成功");
                        getActivity().finish();
                    } else {
                        //该笔订单真实的支付结果，需要依赖服务端的异步通知
                        ToastUtil.showToast(getActivity(), "支付失败");
                        getActivity().finish();
                    }
            }
        }
    };


    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 123);

        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 123: {

                // 用户取消了权限弹窗
                if (grantResults.length == 0) {

                    return;
                }

                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        return;
                    }
                }

                // 所需的权限均正常获取
            }
        }
    }


}
